<template>
  <div class="upload-section">
    <h2 class="section-title">词库导入</h2>
    <div class="help-text">
      <h4>使用说明</h4>
      <p><strong>CSV格式：</strong>英语单词,中文意思</p>
      <p>例如：apple,苹果</p>
      <br>
      <p><strong>TXT格式：</strong>支持一个单词多个含义</p>
      <p>格式：单词 [含义1;含义2;含义3]</p>
      <p>例如：apple [苹果;苹果树;苹果公司]</p>
    </div>
    <div class="file-type-selector">
      <div 
        class="file-type-btn" 
        :class="{ active: currentFileType === 'csv' }"
        @click="switchFileType('csv')"
      >
        CSV文件
      </div>
      <div 
        class="file-type-btn" 
        :class="{ active: currentFileType === 'txt' }"
        @click="switchFileType('txt')"
      >
        TXT文件
      </div>
    </div>
    <div 
      class="upload-area" 
      @click="triggerFileUpload"
      @drop="handleFileDrop"
      @dragover.prevent
    >
      <div class="upload-icon">📁</div>
      <h3>上传{{ currentFileType.toUpperCase() }}词库文件</h3>
      <p>点击选择或拖拽文件到此处</p>
    </div>
    <input 
      type="file" 
      :id="currentFileType + 'File'" 
      :accept="'.' + currentFileType" 
      style="display: none;"
      @change="handleFileUpload"
    >
    <div class="file-inputs">
      <div class="file-input">
        <label>示例词库：</label>
        <button class="btn btn-secondary btn-block" @click="loadSampleWords">加载示例词库</button>
      </div>
    </div>
    <div class="word-list" id="wordList">
      <div class="word-item" v-if="words.length === 0">请先上传词库文件</div>
      <div class="word-item" v-for="(word, index) in words" :key="index">
        <div class="word-text">{{ word.word }}</div>
        <div class="meaning-text">{{ word.meaning }}</div>
      </div>
    </div>
    <div style="margin-top: 25px; text-align: center;">
      <button class="btn btn-success btn-lg" @click="startDictation" :disabled="words.length === 0">开始听写</button>
      <button class="btn btn-warning" @click="resetDictationFunc">重置</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { useDictationStore } from '../composables/useDictation'

interface Word {
  word: string
  meaning: string
}

const dictationStore = useDictationStore()
const resetDictation = dictationStore.resetDictation

// 使用计算属性确保响应性
const words = computed(() => dictationStore.words)

const currentFileType = ref('csv')

const switchFileType = (type: string) => {
  currentFileType.value = type
}

const triggerFileUpload = () => {
  const fileInput = document.getElementById(currentFileType.value + 'File') as HTMLInputElement
  if (fileInput) {
    fileInput.click()
  }
}

const handleFileUpload = async (event: Event) => {
  const input = event.target as HTMLInputElement
  if (!input.files || input.files.length === 0) return
  
  const file = input.files[0]
  const fileExtension = file.name.split('.').pop()?.toLowerCase()
  if (fileExtension !== currentFileType.value) {
    alert(`请选择.${currentFileType.value}格式的文件`)
    return
  }
  
  try {
    const content = await readFileContent(file)
    await parseFileContent(content, currentFileType.value)
  } catch (error) {
    console.error('读取文件失败:', error)
    alert('读取文件失败: ' + error)
  }
}

const handleFileDrop = async (event: DragEvent) => {
  event.preventDefault()
  if (!event.dataTransfer || event.dataTransfer.files.length === 0) return
  
  const file = event.dataTransfer.files[0]
  const fileExtension = file.name.split('.').pop()?.toLowerCase()
  if (fileExtension !== currentFileType.value) {
    alert(`请选择.${currentFileType.value}格式的文件`)
    return
  }
  
  try {
    const content = await readFileContent(file)
    await parseFileContent(content, currentFileType.value)
  } catch (error) {
    console.error('读取文件失败:', error)
    alert('读取文件失败: ' + error)
  }
}

// Helper function to read file content
const readFileContent = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      resolve(e.target?.result as string)
    }
    reader.onerror = (e) => {
      reject(e)
    }
    reader.readAsText(file, 'UTF-8') // 明确指定编码
  })
}

const parseFileContent = async (content: string, fileType: string) => {
  try {
    const parsedWords: Word[] = await invoke('parse_file_content', { content, fileType })
    dictationStore.setWords(parsedWords)
    resetDictation()
  } catch (error) {
    console.error('解析文件失败:', error)
    // 显示更友好的错误信息
    alert('解析文件失败，请确保文件格式正确')
  }
}

const loadSampleWords = async () => {
  try {
    console.log('正在加载示例词库，文件类型:', currentFileType.value)
    const sampleWords: Word[] = await invoke('load_sample_words', { fileType: currentFileType.value })
    console.log('从后端获取的示例词库:', sampleWords)
    
    // 确保数据被正确设置到store
    dictationStore.setWords(sampleWords)
    console.log('词汇已设置到store，当前词汇数量:', dictationStore.words.length)
    
    // 重置听写状态
    resetDictation()
    
    // 添加一个小延迟来确保UI更新
    setTimeout(() => {
      console.log('加载后的词汇列表:', dictationStore.words)
    }, 100)
    
  } catch (error) {
    console.error('加载示例词库失败:', error)
    alert('加载示例词库失败: ' + error)
  }
}

const startDictation = async () => {
  if (words.length === 0) {
    alert('请先加载词库！')
    return
  }
  
  // 重置并开始听写
  dictationStore.startDictation()
  
  // 等待一小段时间确保状态更新完成
  await new Promise(resolve => setTimeout(resolve, 100))
  
  // 触发播放第一个单词的事件
  const event = new CustomEvent('playFirstWord')
  window.dispatchEvent(event)
}

const resetDictationFunc = () => {
  resetDictation()
}
</script>